package com.ByteDance.service.impl;

import com.ByteDance.model.po.CommentEntity;
import com.ByteDance.mapper.CommentMapper;
import com.ByteDance.model.po.Relation;
import com.ByteDance.model.po.UserInfos;
import com.ByteDance.model.po.VideoEntity;
import com.ByteDance.model.vo.Comment;
import com.ByteDance.model.vo.User;
import com.ByteDance.service.ICommentService;
import com.ByteDance.service.IRelationService;
import com.ByteDance.service.IUserService;
import com.ByteDance.service.IVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 * 视频评论表 服务实现类
 * </p>
 *
 * @author  朱哥
 * @since 2024-03-04
 */
@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentEntity> implements ICommentService {
    private final IRelationService iRelationService;
    private final IVideoService iVideoService;
    private final IUserService iUserService;
    @Override
    public CommentEntity PostComment(int userId, int videoId, int actionType, String commentText, Integer commentId) {
//        if (commentText == null) {
//            commentText = ""; // 如果commentText为null，将其设置为空字符串
//        }
        VideoEntity videoEntity = iVideoService.getById(videoId);

        if(actionType == 1){//进行评论，评论数+1
            CommentEntity commentEntity = new CommentEntity();
            commentEntity.setUserId(userId);
            commentEntity.setVideoId(videoId);
            commentEntity.setCommentText(commentText);
            commentEntity.setCreateDate(LocalDate.now());//设置为当前时间
            baseMapper.insert(commentEntity);
            iVideoService.lambdaUpdate()
                    .set(VideoEntity::getCommentCount,videoEntity.getCommentCount() + 1)
                    .eq(VideoEntity::getVideoId,videoId)
                    .eq(VideoEntity::getCommentCount,videoEntity.getCommentCount())//获取到的评论数等于我刚刚获取到的评论数
                    .update();
            return commentEntity;
        }else if(actionType == 2){//删除评论
            //查看要删除的评论是否存在
            CommentEntity commentEntity = lambdaQuery().eq(CommentEntity::getCommentId, commentId).one();
            if(commentEntity == null){
                return null;
            }
            //存在,删除评论，评论数-1
            QueryWrapper<CommentEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId).eq("video_id",videoId).eq("comment_id",commentId);
            baseMapper.delete(queryWrapper);
            iVideoService.lambdaUpdate()
                    .set(VideoEntity::getCommentCount,videoEntity.getCommentCount() - 1)
                    .eq(VideoEntity::getVideoId,videoId)
                    .eq(VideoEntity::getCommentCount,videoEntity.getCommentCount())//获取到的评论数等于我刚刚获取到的评论数
                    .update();
            return commentEntity;
        }
        //不是1也不是2，返回null -- 不合法
        return null;
    }

    @Override
    public Comment[] searchCommentByVideoId(int yid, int videoId) {
        //按发布时间倒序
        List<CommentEntity> list = lambdaQuery().eq(CommentEntity::getVideoId, videoId).orderByDesc(CommentEntity::getCreateDate).list();
        Comment[] comments = new Comment[list().size()];
        for (int i = 0; i < list.size(); i++) {
            CommentEntity commentEntity = list.get(i);
            comments[i] = new Comment();//分配内存空间
            comments[i].setId(commentEntity.getCommentId());
            Integer userId = commentEntity.getUserId();
            UserInfos userInfos = iUserService.getById(userId);
            User user = new User();
            user.setUserId(userId);
            user.setUsername(userInfos.getUsername());
            user.setFollowCount(userInfos.getFollowCount());
            user.setFollowerCount(userInfos.getFollowerCount());
            //查询该userId是否关注了authorId
            boolean flag = true;
            Relation relation = iRelationService.lambdaQuery().eq(Relation::getFollowId, userId).eq(Relation::getFollowerId, yid).one();
            if(relation == null){
                flag = false;
            }
            user.setFollow(flag);
            user.setAvatar(userInfos.getAvatar());
            user.setBackgroundImage(userInfos.getBackgroundImage());
            user.setSignature(userInfos.getSignature());
            user.setTotalFavorited(userInfos.getTotalFavorited());
            user.setWorkCount(userInfos.getWorkCount());
            user.setFavoriteCount(userInfos.getFavoriteCount());
            comments[i].setUser(user);
            comments[i].setContent(commentEntity.getCommentText());
            String createDate = formatCreateDate(commentEntity.getCreateDate());
            comments[i].setCreateDate(createDate);
        }
        
        return comments;
    }

    public String formatCreateDate(LocalDate localDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
        return localDate.format(formatter);
    }


}
